package cn.itcast.web.controller.cargo;

import cn.itcast.common.utils.DownloadUtil;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.vo.ContractProductVo;
import cn.itcast.web.controller.BaseController;
import com.alibaba.dubbo.config.annotation.Reference;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;

@Controller
@RequestMapping("/cargo/contract")
public class OutProductController extends BaseController {

	@Reference
	private ContractService contractService;

	/**
	 * 进入选择日期的页面
	 */
	@RequestMapping("/print")
	public String print() {
		return "cargo/print/contract-print";
	}

	/**
	 * 模板打印
	 */
	@RequestMapping("/printExcelTemplate")
	public void printExcelTemplate(String inputDate) throws IOException {
		//i.查询获取数据列表
		List<ContractProductVo> list = contractService.findByShipTime(inputDate,getLoginCompanyId());
		//ii.通过POI已模板打印的方式创建Excel
		//1.获取模板路径
		String path = session.getServletContext().getRealPath("/")+"/make/xlsprint/tOUTPRODUCT.xlsx";
		//2.根据模板创建工作簿
		Workbook wb = new XSSFWorkbook(path);
		//3.获取第一页
		Sheet sheet = wb.getSheetAt(0);
		//4.处理大标题
		//4.1 获取第一行
		Row row = sheet.getRow(0);
		//4.2 获取第二个单元格
		Cell cell = row.getCell(1);
		//4.3 设置单元格内容
		cell.setCellValue(inputDate.replaceAll("-0","-").
				replaceAll("-","年")+"月份出货表");//2012年8   月份出货表
		//5.处理小标题
		//6.提取模板中数据行的所有样式
		row = sheet.getRow(2);
		CellStyle css [] = new CellStyle[9];
		for (int i = 1; i < 9; i++) {
			cell = row.getCell(i);
			CellStyle cs = cell.getCellStyle(); //css
			css[i] = cs;
		}


		//7.循环数据列表，创建数据行
		int index = 2;
		for (ContractProductVo vo : list) {
			//for (int i = 0; i < 5000; i++) {
				//一个对象，创建一行
				row = sheet.createRow(index);

				//创建客户单元格
				cell = row.createCell(1);
				cell.setCellValue(vo.getCustomName());
				//设置样式
				cell.setCellStyle(css[1]);
				//创建合同号单元格
				cell = row.createCell(2);
				cell.setCellValue(vo.getContractNo());
				cell.setCellStyle(css[2]);
				//创建货号单元格
				cell = row.createCell(3);
				cell.setCellValue(vo.getProductNo());
				cell.setCellStyle(css[3]);
				//创建数量单元格
				cell = row.createCell(4);
				cell.setCellValue(vo.getCnumber());
				cell.setCellStyle(css[4]);
				//创建工厂单元格
				cell = row.createCell(5);
				cell.setCellValue(vo.getFactoryName());
				cell.setCellStyle(css[5]);
				//创建工厂交期单元格
				cell = row.createCell(6);
				String dt = "";
				try {
					dt = new SimpleDateFormat("yyyy-MM-dd").format(vo.getDeliveryPeriod());
				}catch (Exception e) {}
				cell.setCellValue(dt);
				cell.setCellStyle(css[6]);
				//创建船期单元格
				cell = row.createCell(7);
				String st = "";
				try {
					st = new SimpleDateFormat("yyyy-MM-dd").format(vo.getShipTime());
				}catch (Exception e) {}
				cell.setCellValue(st);
				cell.setCellStyle(css[7]);
				//创建贸易条款单元格
				cell = row.createCell(8);
				cell.setCellValue(vo.getTradeTerms());
				cell.setCellStyle(css[8]);

				index++;
			//}
		}

		//iii.完成下载
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		wb.write(bos);//将工作簿中的数据写入bos输出流
		new DownloadUtil().download(bos,response,"出货表.xlsx"); //byteArrayOutputStream字节数组输出流, response对象,文件名称
	}


	/**
	 * 完成出货表Excel文件的生成和下载
	 *  1.文件下载：控制器方法不需要返回值
	 *  2.业务：
	 *      根据输入的船期，查询当前月所有出货我货物信息
	 */
	@RequestMapping("/printExcel")
	public void printExcel(String inputDate) throws IOException {
		//i.查询获取数据列表
		List<ContractProductVo> list = contractService.findByShipTime(inputDate,getLoginCompanyId());
		//ii.通过POI创建Excel文件
		//1.创建工作簿
		//Workbook wb = new XSSFWorkbook();
		Workbook wb = new SXSSFWorkbook(); //百万数据Excel文件创建
		//2.创建第一页
		Sheet sheet = wb.createSheet();
		sheet.setColumnWidth(1,26 * 256);//设置列宽
		sheet.setColumnWidth(2,12* 256);//设置列宽
		sheet.setColumnWidth(3,30* 256);//设置列宽
		sheet.setColumnWidth(4,12* 256);//设置列宽
		sheet.setColumnWidth(5,15* 256);//设置列宽
		sheet.setColumnWidth(6,10* 256);//设置列宽
		sheet.setColumnWidth(7,10* 256);//设置列宽
		sheet.setColumnWidth(8,8* 256);//设置列宽
		sheet.addMergedRegion(new CellRangeAddress(0,0,1,8));//行开始，行结束，列开始，列结束
		//3.创建大标题
		//3.1 创建第一行
		Row row = sheet.createRow(0);
		row.setHeightInPoints(36);//行高
		//3.2 创建第二个单元格
		Cell cell = row.createCell(1);
		//3.3 设置内容         //2015-01 (2015-11)    -->2015-1(2015-11)  -->2015年1
		cell.setCellValue(inputDate.replaceAll("-0","-").
				replaceAll("-","年")+"月份出货表");//2012年8   月份出货表
		cell.setCellStyle(bigTitle(wb));
		//4.创建小标题
		//客户	合同号	货号	数量	工厂	工厂交期	船期	贸易条款
		row = sheet.createRow(1);
		row.setHeightInPoints(24);//行高
		String [] titles = new String[]{"","客户","合同号","货号","数量","工厂","工厂交期","船期","贸易条款"};
		for (int i = 1; i < titles.length; i++) {
			cell = row.createCell(i);
			cell.setCellValue(titles[i]);
			cell.setCellStyle(title(wb));
		}
		//5.循环数据列表，构造数据行
		//设置一个行索引，默认=2
		int index = 2;
		for (ContractProductVo vo : list) {
			//for (int i = 0; i < 5000; i++) {
				//创建一行
				row = sheet.createRow(index);
				row.setHeightInPoints(24);//行高

				//创建客户单元格
				cell = row.createCell(1);
				cell.setCellValue(vo.getCustomName());
				//cell.setCellStyle(text(wb));
				//创建合同号单元格
				cell = row.createCell(2);
				cell.setCellValue(vo.getContractNo());
				//cell.setCellStyle(text(wb));
				//创建货号单元格
				cell = row.createCell(3);
				cell.setCellValue(vo.getProductNo());
				//cell.setCellStyle(text(wb));
				//创建数量单元格
				cell = row.createCell(4);
				cell.setCellValue(vo.getCnumber());
				//cell.setCellStyle(text(wb));
				//创建工厂单元格
				cell = row.createCell(5);
				cell.setCellValue(vo.getFactoryName());
				//cell.setCellStyle(text(wb));
				//创建工厂交期单元格
				cell = row.createCell(6);
				String dt = "";
				try {
					dt = new SimpleDateFormat("yyyy-MM-dd").format(vo.getDeliveryPeriod());
				}catch (Exception e) {}
				cell.setCellValue(dt);
				//cell.setCellStyle(text(wb));
				//创建船期单元格
				cell = row.createCell(7);
				String st = "";
				try {
					st = new SimpleDateFormat("yyyy-MM-dd").format(vo.getShipTime());
				}catch (Exception e) {}
				cell.setCellValue(st);
				//cell.setCellStyle(text(wb));
				//创建贸易条款单元格
				cell = row.createCell(8);
				cell.setCellValue(vo.getTradeTerms());
				//cell.setCellStyle(text(wb));
				index++;
			//}
		}
		//iii.完成下载
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		wb.write(bos);//将工作簿中的数据写入bos输出流
		new DownloadUtil().download(bos,response,"出货表.xlsx"); //byteArrayOutputStream字节数组输出流, response对象,文件名称
	}

	//大标题的样式

	/**
	 * 1.创建单元格的样式对象（cellstyle：可以设置单元格的边框，居中）   cellstyle（单元格样式）
	 * 2.创建字体对象（font：描述字体格式，字号）                      font(字体)
	 * 3.向样式对象中设置字体格式                                     将font存入cellstyle
	 * 4.向单元格中设置样式                                           将cellstyle设置到cell单元格中
	 *
	 *
	 * @param wb
	 * @return
	 */
	public CellStyle bigTitle(Workbook wb){
		CellStyle style = wb.createCellStyle();
		Font font = wb.createFont();
		font.setFontName("宋体");
		font.setFontHeightInPoints((short)16);
		font.setBold(true);//字体加粗
		style.setFont(font);
		style.setAlignment(HorizontalAlignment.CENTER);				//横向居中
		style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
		return style;
	}

	//小标题的样式
	public CellStyle title(Workbook wb){
		CellStyle style = wb.createCellStyle();
		Font font = wb.createFont();
		font.setFontName("黑体");
		font.setFontHeightInPoints((short)12);
		style.setFont(font);
		style.setAlignment(HorizontalAlignment.CENTER);				//横向居中
		style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
		style.setBorderTop(BorderStyle.THIN);						//上细线
		style.setBorderBottom(BorderStyle.THIN);					//下细线
		style.setBorderLeft(BorderStyle.THIN);						//左细线
		style.setBorderRight(BorderStyle.THIN);						//右细线
		return style;
	}

	//文字样式
	public CellStyle text(Workbook wb){
		CellStyle style = wb.createCellStyle();
		Font font = wb.createFont();
		font.setFontName("Times New Roman");
		font.setFontHeightInPoints((short)10);

		style.setFont(font);

		style.setAlignment(HorizontalAlignment.LEFT);				//横向居左
		style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
		style.setBorderTop(BorderStyle.THIN);						//上细线
		style.setBorderBottom(BorderStyle.THIN);					//下细线
		style.setBorderLeft(BorderStyle.THIN);						//左细线
		style.setBorderRight(BorderStyle.THIN);						//右细线

		return style;
	}
}
